<template>
	<div class="html2canvas">
		<div id="html2Image" v-if="!showImgBox">
			<img
				class="cover"
				crossorigin="anonymous"
				src="https://vod.hbrhcloud.com/asset/3ae317afac72bba29be44beb21339a4a/cover/Cover0.jpg"
			/>

			<div @click="openDialog">弹窗</div>
			<div class="modal" v-if="showDialog">
				<div id="qrcode"></div>
				<div class="btn" @click="saveToImg()">保存</div>
			</div>
		</div>
		<div class="img-box" v-if="showImgBox">
			<img :src="imgUrl" />
		</div>
	</div>
</template>

<script>
import html2canvas from 'html2canvas';
import QRCode from 'qrcodejs2';

export default {
	name: 'html2canvas',
	data() {
		return {
			showDialog: false,
			showImgBox: false,
            imgUrl:''
		};
	},
	methods: {
		openDialog() {
			this.showDialog = true;
			this.$nextTick(() => {
				let qrcode = new QRCode('qrcode', {
					width: 132,
					height: 132,
					text: 'https://www.baidu.com', // 二维码地址
					colorDark: '#000',
					colorLight: '#fff',
				});
			});
		},
		// 保存图片
		saveToImg() {
			let that = this;
			const element = document.getElementById('html2Image'); // 需要导出的页面
			html2canvas(element, {
				allowTaint: true, // 是否允许跨域图片污染画布
				useCORS: true, // 是否允许跨域图片加载
			}).then((canvas) => {
				// imgUrl 是图片的 base64格式 代码 png 格式
				const imgUrl = canvas.toDataURL('image/png');
				this.createImage(imgUrl, 'plantCardImg.png');
				//下载图片的功能。
				// this.downloadIamge(imgUrl, 'plantCardImg.png');
			});
		},
		//下载图片
		downloadIamge(imgsrc, name) {
			const image = new Image();
			// 解决跨域 Canvas 污染问题
			image.setAttribute('crossOrigin', 'anonymous');
			image.onload = function () {
				let canvas = document.createElement('canvas');
				canvas.width = image.width;
				canvas.height = image.height;
				const context = canvas.getContext('2d');
				context.drawImage(image, 0, 0, image.width, image.height);
				const url = canvas.toDataURL('image/png'); //得到图片的base64编码数据
				const a = document.createElement('a'); // 生成一个a元素
				const event = new MouseEvent('click'); // 创建一个单击事件
				a.download = name || 'photo'; // 设置图片名称
				a.href = url; // 将生成的URL设置为a.href属性
				a.dispatchEvent(event); // 触发a的单击事件
			};
			image.src = imgsrc;
		},
		// 创建图片应对微信下载
		createImage(imgsrc, name) {
			let that = this;
			const image = new Image();
			// 解决跨域 Canvas 污染问题
			image.setAttribute('crossOrigin', 'anonymous');
			image.onload = function () {
                that.imgUrl = imgsrc;
				that.showImgBox = true;
			};
			image.src = imgsrc;
		},
	},
};
</script>

<style lang="scss" scoped>
.cover {
	width: 100%;
	height: 500px;
}
.modal {
	position: fixed;
	top: 50%;
	left: 50%;
	width: 80%;
	height: 300px;
	transform: translate(-50%, -50%);
	z-index: 2;
	background: #ccc;
}
.btn {
	width: 60px;
	height: 38px;
	margin: 0 auto;
	border: 1px solid #000;
}

.img-box {
	position: fixed;
	left: 0;
	top: 0;
	z-index: 9;

    img{
        width: 100%;
    }
}
</style>
